<template>
    <div class="serial-port-setting">
        <h2 class="title">串口配置</h2>
        
        <div class="form-section">
            <div class="section-title">本机串口配置：</div>
            
            <div class="form-item">
                <label class="form-label">串口</label>
                <a-select
                    v-model="portValue"
                    size="small"
                    placeholder="请选择"
                    :disabled="isDisabled"
                    style="width: 100%;"
                    @focus="handleSerialPortFocus"
                >
                    <a-select-option
                        v-for="item in serialPorts"
                        :key="item.value"
                        :value="item.value"
                    >
                        {{ item.label }}
                    </a-select-option>
                </a-select>
            </div>

            <div class="form-item">
                <label class="form-label">波特率</label>
                <a-select
                    v-model="baudValue"
                    size="small"
                    placeholder="请选择"
                    :disabled="isDisabled"
                    style="width: 100%;"
                >
                    <a-select-option
                        v-for="item in serialBaud"
                        :key="item"
                        :value="item"
                    >
                        {{ item }}
                    </a-select-option>
                </a-select>
            </div>

            <div class="form-item">
                <label class="form-label">数据位</label>
                <a-select
                    v-model="dataValue"
                    size="small"
                    placeholder="请选择"
                    :disabled="isDisabled"
                    style="width: 100%;"
                >
                    <a-select-option
                        v-for="item in serialData"
                        :key="item"
                        :value="item"
                    >
                        {{ item }}
                    </a-select-option>
                </a-select>
            </div>

            <div class="form-item">
                <label class="form-label">检验位</label>
                <a-select
                    v-model="parityValue"
                    size="small"
                    placeholder="请选择"
                    :disabled="isDisabled"
                    style="width: 100%;"
                >
                    <a-select-option
                        v-for="item in serialInspection"
                        :key="item"
                        :value="item"
                    >
                        {{ item }}
                    </a-select-option>
                </a-select>
            </div>

            <div class="form-item">
                <label class="form-label">停止位</label>
                <a-select
                    v-model="stopValue"
                    size="small"
                    placeholder="请选择"
                    :disabled="isDisabled"
                    style="width: 100%;"
                >
                    <a-select-option
                        v-for="item in serialStop"
                        :key="item"
                        :value="item"
                    >
                        {{ item }}
                    </a-select-option>
                </a-select>
            </div>
        </div>

        <div class="form-section">
            <div class="section-title">PLC串口配置：</div>
            
            <div v-if="false" class="form-item">
                <label class="form-label">产品类型</label>
                <a-select 
                    v-model="targetDevValue" 
                    size="small" 
                    placeholder="请选择" 
                    :disabled="isDisabled" 
                    style="width: 100%;"
                    @change="handleSelectDev"
                >
                    <a-select-option
                        v-for="item in targetDevs"
                        :key="item.value"
                        :value="item.value"
                    >
                        {{ item.label }}
                    </a-select-option>
                </a-select>
            </div>

            <div class="form-item">
                <label class="form-label">设备串口</label>
                <a-select 
                    v-model="targetPortValue" 
                    size="small" 
                    placeholder="请选择" 
                    :disabled="isDisabled"
                    style="width: 100%;"
                >
                    <a-select-option
                        v-for="item in targetPorts"
                        :key="item.value"
                        :value="item.value"
                    >
                        {{ item.label }}
                    </a-select-option>
                </a-select>
            </div>
        </div>

        <div class="form-item">
            <a-button 
                type="primary" 
                size="small" 
                ghost 
                @click="handleOpen"
            >
                {{ linkButtonText }}
            </a-button>
        </div>
    </div>
</template>
    
<script>
import DeviceTabManager from '@/api/TabManager/DeviceTabManager'

export default {
    name: 'SerialPortSetting',
    data() {
        return {
            deviceTabManager: new DeviceTabManager(),
            linkButtonText: '打开串口',
            isOpen: false,
            portValue: '',
            baudValue: '115200',
            dataValue: '7',
            parityValue: 'Even',
            stopValue: '1',
            targetPortValue: '',
            targetDevValue: '',
            isDisabled: false,
            serialPorts: [],
            serialBaud: ['9600', '19200', '38400', '57600', '115200'],
            serialData: ['5', '6', '7', '8'],
            serialInspection: ['None', 'Even', 'Odd', 'Mark', 'Space'],
            serialStop: ['1', '1.5', '2'],
            targetPorts: [],
            targetDevs: [],
            mapTargetPorts: new Map()
        }
    },
    watch: {
        serialPorts(newValue) {
            if (newValue.length > 0) {
                this.portValue = newValue[0].value
            }
        }
    },
    created() {
        console.log('🔍 [SerialPortSetting] 组件创建')
        this.updateTargetPortToUI('9')
        this.loadSerialPorts()
    },
    
    mounted() {
        console.log('🔍 [SerialPortSetting] 组件挂载完成')
        console.log('🔍 [SerialPortSetting] 当前串口数据:', this.serialPorts)
        console.log('🔍 [SerialPortSetting] 当前选中串口:', this.portValue)
    },  
    methods: {
        async loadSerialPorts() {
            try {
                console.log('🔍 [SerialPortSetting] 加载串口列表')
                const response = await this.deviceTabManager.getSerialPortList()
                console.log('🔍 [SerialPortSetting] API响应:', response)
                
                if (response.code === 0) {
                    console.log('🔍 [SerialPortSetting] 原始数据:', response.data)
                    console.log('🔍 [SerialPortSetting] 数据类型:', typeof response.data)
                    
                    let serialPortNames = []
                    if (typeof response.data === 'string') {
                        serialPortNames = JSON.parse(response.data)
                    } else if (Array.isArray(response.data)) {
                        serialPortNames = response.data
                    } else {
                        console.warn('⚠️ [SerialPortSetting] 未知的数据格式:', response.data)
                        serialPortNames = []
                    }
                    
                    console.log('✅ [SerialPortSetting] 解析后的串口列表:', serialPortNames)
                    
                    // 转换为组件需要的格式
                    this.serialPorts = serialPortNames.map(port => ({
                        value: port,
                        label: port
                    }))
                    
                    console.log('✅ [SerialPortSetting] 转换后的串口数据:', this.serialPorts)
                    
                    // 默认选择第一个串口
                    if (this.serialPorts.length > 0) {
                        this.portValue = this.serialPorts[0].value
                        console.log('✅ [SerialPortSetting] 默认选择串口:', this.portValue)
                    } else {
                        console.warn('⚠️ [SerialPortSetting] 没有可用的串口')
                    }
                } else {
                    console.error('❌ [SerialPortSetting] 获取串口列表失败:', response.msg || response.message)
                    this.$message.error('获取串口列表失败: ' + (response.msg || response.message || '未知错误'))
                }
            } catch (error) {
                console.error('❌ [SerialPortSetting] 加载串口列表异常:', error)
                
                // 如果是 CEFSharp 环境不可用，提供模拟数据用于测试
                if (error.message && error.message.includes('cefSharp环境不可用')) {
                    console.log('🔧 [SerialPortSetting] CEFSharp环境不可用，使用模拟数据')
                    this.serialPorts = [
                        { value: 'COM1', label: 'COM1' },
                        { value: 'COM2', label: 'COM2' },
                        { value: 'COM3', label: 'COM3' }
                    ]
                    if (this.serialPorts.length > 0) {
                        this.portValue = this.serialPorts[0].value
                    }
                    return
                }
                
                this.$message.error('获取串口列表失败: ' + (error.message || '未知错误'))
            }
        },
        
        handleSerialPortFocus() {
            console.log('🔍 [SerialPortSetting] 串口下拉框获得焦点')
            // 只有在串口列表为空时才重新加载
            if (this.serialPorts.length === 0) {
                console.log('🔍 [SerialPortSetting] 串口列表为空，重新加载')
                this.loadSerialPorts()
            } else {
                console.log('🔍 [SerialPortSetting] 串口列表已存在，跳过加载')
            }
        },
        
        handleOpen() {
            this.isOpen = !this.isOpen
            console.log('handleOpen button open:', this.isOpen)
            this.linkButtonText = '打开串口'
            if (this.isOpen) {
                this.linkButtonText = '关闭串口'
            }
            
            const params = {
                port: this.portValue,
                baud: this.baudValue,
                data: this.dataValue,
                parity: this.parityValue,
                stop: this.stopValue,
                target: this.targetPortValue
            }
            this.isDisabled = this.isOpen
            this.$emit(
                'isConnect',
                this.isDisabled,
                JSON.stringify(params)
            )
        },
        updatePortValue() {
            if (this.serialPorts.length > 0) {
                this.portValue = this.serialPorts[0].value
            }
        },
        updateTargetPortValue(data) {
            let para = JSON.parse(data)
    
            // 遍历对象数组，以label的值作为键，构建映射
            para.forEach(item => {
                this.mapTargetPorts.set(item.label, item.value)
                this.targetPorts.push(item.label)
                this.targetDevs.push({ 'label': item.label, 'value': item.label })
            })

            if (this.targetDevs.length > 0) {
                this.targetDevValue = this.targetDevs[0].label
            } 

            if (this.targetPorts.length > 0) {
                let target = this.getTargetPortLimitValue(this.targetPorts[0])
                this.updateTargetPortToUI(target)
            }
        },

        getTargetPortLimitValue(value) {    
            if (this.mapTargetPorts.has(value)) {
                return this.mapTargetPorts.get(value)
            } else {
                return '0'
            }
        },

        stringToInt(str) {
            // 检查数据是否为字符串
            if (typeof str !== 'string') {
                console.log('数据不是字符串')
                return 0
            }

            // 使用parseInt函数将字符串转换为整数
            // 第二个参数指定转换的进制，这里使用10进制
            let intData = parseInt(str, 10)

            // 检查是否成功转换为整数
            if (isNaN(intData)) {
                console.log('无法将字符串转换为整数')
                return 0
            }

            return intData
        },

        updateTargetPortToUI(data) {
            let value = this.stringToInt(data)
            let temp = ''
            this.targetPorts = []
            for (let index = 0; index < value; index++) {
                temp = 'COM' + (index + 1).toString()
                this.targetPorts.push({ 'label': temp, 'value': temp })
            }
            if (this.targetPorts.length > 0) {
                this.targetPortValue = this.targetPorts[0].label
            }
        },

        handleSelectDev(value) {
            let target = this.getTargetPortLimitValue(value)
            this.updateTargetPortToUI(target)
        },

        updateStatus(bOpen) {
            console.log('🔍 [SerialPortSetting] 更新状态:', bOpen)
            if (bOpen === 'False') {
                // 连接失败时，重置为未连接状态
                this.isOpen = false
                this.linkButtonText = '打开串口'
                this.isDisabled = false
                this.$notification.warning({
                    message: '警告',
                    description: '打开串口失败'
                })
            }
        },
        updatePorts(value) {
            let param = JSON.parse(value)
            this.targetPortValue = param.com
            this.baudValue = param.bandRate
            this.dataValue = param.dateBits
            this.parityValue = param.parity
            this.stopValue = param.stopBit
        }    
    }
}
</script>
    
<style scoped lang="scss">
.serial-port-setting {
    background: white;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    max-width: 600px;
    margin: 0 auto;
}
.title {
    text-align: left;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #333;
}
.form-section {
    margin-bottom: 20px;
}
.section-title {
    font-weight: 500;
    color: #666;
    margin-bottom: 15px;
    font-size: 14px;
}
.form-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
}
.form-label {
    width: 80px;
    text-align: right;
    margin-right: 15px;
    font-size: 14px;
    color: #333;
    flex-shrink: 0;
}

// 覆盖 Ant Design 的默认样式
:deep(.ant-select) {
    flex: 1;
}
:deep(.ant-input) {
    flex: 1;
}
</style>
    